<template>
  <div class="content-wapper">
    <a-tabs :activeKey="defaultActiveKey" @change="tabCallback">
      <a-tab-pane key="1" tab="账号审核">
        <!-- 主播管理 -->
        <a-spin class="anchor-review" tip="加载中..." :spinning="isLoading">
          <!-- 筛选 -->
          <div class="filter">
            <div class="l">
              <span>主播：</span>
              <a-input-search style="width:240px;margin-right:16px" type="text" placeholder="输入主播姓名/手机号" allowClear v-model="anchorQuery.keyWord" @search="handleByQueryCond" />
              <span>状态：</span>
              <a-select style="width:160px;margin-right:16px" placeholder="请选择状态" v-model="anchorQuery.status" @change="handleByQueryCond">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="item in anchorPersonalStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
              </a-select>
              <span>申请时间：</span>
              <a-range-picker @change="handleByQueryCond" v-model="anchorQuery.selectDate" />
            </div>
            <div class="r">
              <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
            </div>
          </div>
          <!-- <div class="remind-text">*账号审核通过后，需要操作“合作模式设置”，提交审核成功后账号可正常使用。（审核状态请切换到“合作模式审核”页面）</div> -->
          <!-- 表格 -->
          <div class="main-body">
            <account-table :dataSource="anchorList">
              <template slot="action" slot-scope="{ row }">
                <!-- <a-button type="link" v-if="row.showCooperateSet" @click="cooperationSetFn(row, true, 1)">合作模式设置</a-button> -->
                <a-button type="link" style="padding:0;margin-right:10px" @click="handleSeeAnchorDesc(row)">详情</a-button>
                <a-button type="link" v-if="row.status === 1" style="padding:0" @click="handleSeeAnchorReviewDesc(row)">审核</a-button>
              </template>
            </account-table>
          </div>

          <!-- 分页 -->
          <div class="paging-container">
            <a-pagination
              :pageSize="anchorQuery.pageSize"
              v-model="anchorQuery.pageIndex"
              :total="anchorTotal"
              showQuickJumper
              showLessItems
              :showTotal="(total) => `共 ${total} 条`"
              style="margin: 10px auto;"
              @change="handlePageChange"
            />
          </div>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane key="2" tab="合作模式审核">
        <a-spin class="anchor-review" tip="加载中..." :spinning="iscoopLoading">
          <!-- 筛选 -->
          <div class="filter">
            <div class="l">
              <span>主播：</span>
              <a-input-search style="width:240px;margin-right:16px" type="text" placeholder="输入主播姓名/手机号" allowClear v-model="coopQuery.keyWord" @search="handleByCoopQueryCond" />
              <span>状态：</span>
              <a-select style="width:160px;margin-right:16px" placeholder="请选择状态" v-model="coopQuery.status" @change="handleByCoopQueryCond">
                <a-select-option value="">全部</a-select-option>
                <a-select-option v-for="item in peopleStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
              </a-select>
              <span>申请时间：</span>
              <a-range-picker @change="handleByCoopQueryCond" v-model="coopQuery.selectDate" />
            </div>

            <div class="r">
              <a-button @click="handleByCoopQueryCond" type="primary" style="background:#1d6fe9">查询</a-button>
            </div>
          </div>
          <div class="remind-text">*合作模式审核流程：提交审核—>李佳霓审核—>任林艳审核—>完成—>主播可正常使用账号</div>
          <!-- 表格 -->
          <div class="main-body">
            <cooper-table :dataSource="cooperList">
              <template slot="action" slot-scope="{ row }">
                <a-button style="padding:0" type="link" @click="cooperationSetFn(row, false, 2)">详情</a-button>
                <a-button v-if="row.status === 3 || row.status === 4" style="padding:0" type="link" @click="cooperationSetFn(row, true, 2)">重新提交</a-button>
              </template>
            </cooper-table>
          </div>

          <!-- 分页 -->
          <div class="paging-container">
            <a-pagination
              :pageSize="coopQuery.pageSize"
              v-model="coopQuery.pageIndex"
              :total="cooperTotal"
              showQuickJumper
              showLessItems
              :showTotal="(total) => `共 ${total} 条`"
              style="margin: 10px auto;"
              @change="handlePageChangeCooper"
            />
          </div>
        </a-spin>
      </a-tab-pane>
    </a-tabs>
    <!-- 审核或查看详情弹窗 -->
    <audit-detail v-model="isAnchorDescModalShow" :type="isReviewOrSeeDesc" :anchorDesc="anchorDesc" @onChange="getChooseId" @onCancel="handleAnchorInfoCancel">
      <template slot="footer">
        <template v-if="isReviewOrSeeDesc" style="display:flex;justify-content: center;">
          <a-button type="danger" style="background:#F55F4E" @click="handleAnchorReview(false)">驳回</a-button>
          <a-button type="primary" style="background:#1D6FE9" @click="handleAnchorReview(true)">通过</a-button>
        </template>
        <a-button v-else type="primary" style="background:#1D6FE9" @click="handleAnchorInfoCancel">关闭</a-button>
      </template>
    </audit-detail>
    <!-- 合作模式审核详情 -->
    <cooper-detail :cooperDesc="cooperInfo" v-model="isShowCooperDetail" @cancel="isShowCooperDetail = false">
      <template slot="footer">
        <a-button type="primary" style="background:#1D6FE9;" @click="isShowCooperDetail = false">关闭</a-button>
      </template>
    </cooper-detail>
    <!-- 合作设置 -->
    <a-modal class="copy-modal" width="680px" :footer="null" :visible="cooperationSetModal" @cancel="closeCooper" title="合作设置">
      <a-spin tip="提交中..." :spinning="isSubLoading">
        <div class="apply-type">
          <Title :conf="{ title: '合作信息', src: require('@/assets/images/icon_hzsz_hzxx@3x.png') }" class="margin-bott-10" :fontSize="16" :imgWidth="22" :imgHieght="22" />
          <div class="apply-type-box">
            <a-form-model ref="cooperationSetModalForm" :model="cooperationSetModalForm" :rules="coopRules" :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item label="结算类型：" prop="settlementType">
                    <a-select v-model="cooperationSetModalForm.settlementType" :disabled="!noBtn" @change="changeCashTypeCoop" class="filter-select" placeholder="请选择结算类型">
                      <a-select-option value="1">A</a-select-option>
                      <a-select-option value="2">B</a-select-option>
                      <a-select-option value="3">C</a-select-option>
                      <a-select-option value="4">D</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12" v-show="showMoneyCoop">
                  <a-form-model-item :label="moneyLabelCoop" prop="money"> <a-input :disabled="!noBtn" v-model="cooperationSetModalForm.money"></a-input></a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item prop="cooperateStartTime" label="合作时间：" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
                    <a-range-picker :disabledDate="disabledDate" :disabled="!noBtn" v-model="cooperationSetModalForm.selectDate" />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item style="margin-bottom:-5px;" label="合同" prop="contractUrl" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
                    <upload :limit="9" v-model="cooperationSetModalForm.contractUrl" :disabled="!noBtn"></upload>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="备注" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
                    <a-input v-model="cooperationSetModalForm.remark" type="textarea" :disabled="!noBtn"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="上传截图：" :label-col="{ span: 4 }" :wrapper-col="{ span: 19 }">
                    <upload :limit="9" v-model="cooperationSetModalForm.contractImageUrl" :disabled="!noBtn"></upload>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </div>
        <div style="display:flex;justify-content: center;" v-if="noBtn">
          <a-button type="" @click="closeCooper()" style="border-color: #1D6FE9;color: #1D6FE9;margin-right:32px;">关闭</a-button>
          <a-button type="primary" @click="submitCoop(1)" style="background:#1D6FE9">提交审核</a-button>
        </div>
        <div style="display:flex;justify-content: center;" v-else>
          <a-button type="primary" @click="closeCooper()" style="background:#1D6FE9">关闭</a-button>
        </div>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import {
  getAnchorReviewList as getAnchorReviewListApi,
  getAnchorReviewDesc as getAnchorReviewDescApi,
  setAnchorReview as setAnchorReviewApi,
  cooperateSet,
  cooperateDetail,
  auditApplyList
} from '@/service'
import upload from '@/components/upload/upload'
import moment from 'moment'
import accountTable from './accountTable'
import auditDetail from './auditDetail'
import cooperTable from './cooperTable'
import cooperDetail from './cooperDetail'
import { anchorPersonalStatus, peopleStatus } from './auditConfig'
const g = function(row = {}) {
  return {
    selectDate: row.selectDate || [],
    contractUrl: row.contractUrl || [],
    money: row.money ? (row.money / 100).toFixed(2) : '',
    contractImageUrl: row.contractImageUrl || [],
    remark: row.remark || '',
    accountType: row.accountType || '',
    agentId: row.agentId || '',
    id: row.id || '',
    settlementType: row.settlementType ? String(row.settlementType) : undefined
  }
}
export default {
  name: 'anchorReview',
  data() {
    let checkDate = (rule, value, callback) => {
      const { selectDate = [] } = this.cooperationSetModalForm
      if (selectDate && selectDate.length > 0) {
        callback()
      } else {
        callback(new Error('请选择合作时间'))
      }
    }
    let checkMoney = (rule, value, callback) => {
      var pattern = /^\d+(\.\d+)?$/
      if (!value) {
        callback(new Error('请输入金额'))
      } else if (!pattern.test(value) && value) {
        callback(new Error('金额格式有误'))
      } else {
        callback()
      }
      // callback()
    }
    return {
      defaultActiveKey: '1',
      moment,
      showMoneyCoop: false,
      noBtn: false,
      moneyLabelCoop: '金额',
      // 提交合作设置的loading
      isSubLoading: false,
      // loading是否显示
      isLoading: false,
      iscoopLoading: false,
      isShowCooperDetail: false,
      coopQuery: {
        // 当前页 （最小为1） 必须传入
        pageIndex: 1,
        // 每页大小 （最大为100） 必须传入
        pageSize: 10,
        // 0李佳霓审核中;1任林艳审核中;2已通过;3李佳霓已驳回;4任林艳已驳回
        status: '',
        // 关键字查询 （电话号码等值查询；达人id模糊查询；主播姓名模糊查询）
        keyWord: '',
        selectDate: []
      },
      cooperList: [],
      cooperTotal: 0,
      // table数据查询条件
      anchorQuery: {
        // 当前页 （最小为1） 必须传入
        pageIndex: 1,
        // 每页大小 （最大为100） 必须传入
        pageSize: 10,
        // 1-待审核;2-已通过;3-已驳回
        status: '',
        // 关键字查询 （电话号码等值查询；达人id模糊查询；主播姓名模糊查询）
        keyWord: '',
        selectDate: []
      },
      anchorPersonalStatus: anchorPersonalStatus || [],
      peopleStatus: peopleStatus || [],
      // 主播列表
      anchorList: [],
      // 主播列表总数据条数
      anchorTotal: 0,
      // 主播详情弹窗是否显示
      isAnchorDescModalShow: false,
      // 主播详情数据
      anchorDesc: {},
      // 是审核还是查看详情：0-查看详情；1-审核
      isReviewOrSeeDesc: 0,
      tabType: 1,
      // 合作设置
      cooperationSetModal: false,
      cooperationSetModalForm: g(),
      cooperInfo: {},
      coopRules: {
        settlementType: [
          {
            required: true,
            message: '请选择结算类型',
            trigger: 'blur'
          }
        ],
        cooperateStartTime: [{ validator: checkDate, trigger: 'blur', message: '请设置合同时间', required: true }],
        contractUrl: [{ required: true, message: '请上传合同', trigger: 'blur' }],
        money: [
          {
            validator: checkMoney,
            required: true,
            message: '请输入金额',
            trigger: 'blur'
          }
        ]
      }
    }
  },

  components: {
    upload,
    accountTable,
    auditDetail,
    cooperTable,
    cooperDetail
  },

  methods: {
    tabCallback(key) {
      this.defaultActiveKey = key
      if (key === '1') {
        this.getAnchorReviewList()
      } else if (key === '2') {
        this.getCooperReviewList()
      }
    },
    disabledDate(current) {
      return current <= moment().subtract(1, 'day') // 今天之后的年月日不可选，不包括今天
    },
    getChooseId(e = '') {
      this.auditChannelManagerId = e
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.anchorQuery.pageIndex = 1
      this.getAnchorReviewList()
    },

    handleByCoopQueryCond() {
      this.coopQuery.pageIndex = 1
      this.getCooperReviewList()
    },

    /**
     * 主播审核
     * @param {boolean} isRejectAdopt true-通过，false-驳回
     * @returns {void}
     */
    handleAnchorReview(isRejectAdopt) {
      const {
        anchorDesc: { applyType, id },
        $messageSend,
        $confirm,
        getAnchorReviewList,
        handleAnchorInfoCancel,
        auditChannelManagerId
      } = this
      // if (!auditChannelManagerId && isRejectAdopt) {
      //   this.$messageSend.error('请选择渠道经理')
      //   return
      // }
      $confirm({
        title: '提示',
        content: '确定进行操作吗？',
        onOk: () => {
          // 发送请求
          return setAnchorReviewApi({ applyType, id, status: isRejectAdopt ? 2 : 3, auditChannelManagerId })
            .then((rs) => {
              handleAnchorInfoCancel()
              getAnchorReviewList()
              $messageSend.success('操作成功')
            })
            .catch((err) => err)
        }
      })
    },

    /**
     * 查看主播审核详情数据
     * @param {object} data 被操作的数据
     * @returns {void}
     */
    handleSeeAnchorReviewDesc({ applyType, id }) {
      this.getAnchorReviewDesc(applyType, id).then(() => {
        this.isReviewOrSeeDesc = 1
        this.isAnchorDescModalShow = true
      })
    },

    /**
     * 关闭查看主播详情数据
     * @returns {void}
     */
    handleAnchorInfoCancel() {
      this.isAnchorDescModalShow = false
    },

    /**
     * 查看主播详情数据
     * @param {object} data 被操作的数据
     * @returns {void}
     */
    handleSeeAnchorDesc({ applyType, id }) {
      this.getAnchorReviewDesc(applyType, id).then(() => {
        this.isReviewOrSeeDesc = 0
        this.isAnchorDescModalShow = true
      })
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.anchorQuery.pageIndex = num
      this.getAnchorReviewList()
    },
    handlePageChangeCooper(num) {
      this.coopQuery.pageIndex = num
      this.getCooperReviewList()
    },

    /**
     * 查看主播详情数据
     * @param {number} applyType 申请人类型 ：1个人 ，2公司
     * @param {number} id id
     * @returns {Promise<void>}
     */
    getAnchorReviewDesc(applyType, id) {
      this.isLoading = true

      return getAnchorReviewDescApi({ applyType, id })
        .then((rs) => {
          this.anchorDesc = Object.freeze(rs)
        })
        .finally(() => {
          this.isLoading = false
        })
    },

    /**
     * 获取主播信息列表
     * 具体参数参考 getAnchorReviewListApi 方法
     * @returns {Promise<void>}
     */
    getAnchorReviewList() {
      this.isLoading = true
      return getAnchorReviewListApi(this.getParams())
        .then((rs) => {
          this.anchorList = Object.freeze(rs.anchorsAuditListData) || []
          this.anchorTotal = rs.total || 0

          setTimeout(() => {
            this.setPathParams(this.getParams())
          }, 0)
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    getCooperReviewList() {
      this.iscoopLoading = true
      return auditApplyList(this.getCooperParams())
        .then((rs) => {
          this.cooperList = Object.freeze(rs.cooperateListDate) || []
          this.cooperTotal = rs.total || 0
        })
        .finally(() => {
          this.iscoopLoading = false
        })
    },
    // 合作设置 tabType 1 tab1  2 tab2
    cooperationSetFn(item = {}, BtnType = false, tabType = 1) {
      const { id } = item
      this.noBtn = BtnType
      this.cooperationSetModalForm.agentId = id
      this.tabType = tabType
      this.getCoopDetail().then((res = {}) => {
        const { settlementType } = res
        if (settlementType !== 4) {
          this.showMoneyCoop = true
        } else {
          this.showMoneyCoop = false
        }
        if (tabType === 2 && !this.noBtn) {
          this.isShowCooperDetail = true
        } else {
          this.cooperationSetModal = true
        }
      })
    },
    changeCashTypeCoop(e) {
      if (e === '1' || e === '2') {
        this.showMoneyCoop = true
        this.moneyLabelCoop = '坑位费'
      } else if (e === '3') {
        this.showMoneyCoop = true
        this.moneyLabelCoop = '车马费'
      } else {
        this.showMoneyCoop = false
      }
    },
    closeCooper() {
      this.cooperationSetModal = false
      let form = this.$refs.cooperationSetModalForm
      if (form && form.clearValidate) {
        this.$nextTick(() => {
          form.clearValidate()
        })
      }
    },
    // 获取合作设置信息
    getCoopDetail() {
      const { agentId } = this.cooperationSetModalForm || {}
      return new Promise((resolve) => {
        cooperateDetail({
          id: agentId
        })
          .then((res = {}) => {
            const { cooperateEndTime, cooperateStartTime } = res
            this.cooperationSetModalForm = g(res)
            if (this.tabType === 2 && !this.noBtn) {
              this.cooperInfo = res
            }
            if (cooperateEndTime && cooperateStartTime) {
              this.cooperationSetModalForm.selectDate = [cooperateStartTime, cooperateEndTime]
            }
            this.cooperationSetModalForm.agentId = agentId
            resolve(res)
          })
          .catch((error) => {
            console.log(error)
          })
      })
    },
    // 提交合作设置 status 0 草稿 1 提交审核
    submitCoop(status = 1) {
      this.$refs.cooperationSetModalForm.validate((valid, obj = {}) => {
        let isValid = false
        if (status === 0) {
          isValid = true
          this.$refs.cooperationSetModalForm.clearValidate()
        } else {
          isValid = valid
        }
        if (this.cooperationSetModalForm.settlementType === '4') {
          this.$refs.cooperationSetModalForm.clearValidate(['money'])
          this.cooperationSetModalForm.money = ''
          if (obj && obj.money) {
            isValid = true
          }
        }
        if (isValid) {
          const { agentId, accountType, id, contractUrl, remark, selectDate = [], settlementType, contractImageUrl, money } = this.cooperationSetModalForm || {}
          const postParams = {
            id,
            agentId,
            accountType,
            contractUrl,
            settlementType,
            contractImageUrl,
            money: money ? money * 100 : '',
            remark,
            cooperateStartTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
            cooperateEndTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
          }
          this.isSubLoading = true
          cooperateSet(postParams)
            .then((res) => {
              if (this.tabType === 1) {
                this.getAnchorReviewList()
              } else {
                this.getCooperReviewList()
              }
              this.cooperationSetModal = false
              this.cooperationSetModalForm = g({})
            })
            .finally(() => {
              this.isSubLoading = false
            })
        }
      })
    },
    // 拿参数
    getParams() {
      const { status, selectDate, keyWord, pageIndex, pageSize } = this.anchorQuery
      return {
        pageIndex,
        pageSize,
        status,
        keyWord,
        startTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },
    // 拿参数
    getCooperParams() {
      const { status, selectDate, keyWord, pageIndex, pageSize } = this.coopQuery
      return {
        pageIndex,
        pageSize,
        status,
        keyWord,
        startTime: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endTime: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    }
  },
  mounted() {
    this.getAnchorReviewList()
  }
}
</script>

<style lang="less" scoped>
.content-wapper {
  width: 100%;
  height: 100%;
  // overflow-y: auto !important;
}

/deep/ .ant-descriptions-item-label {
  color: #666;
}

/deep/ .ant-descriptions-item-content {
  color: #333;
}

/deep/ .ant-tabs {
  padding: 16px 16px 0 16px;
}
/deep/ .ant-tabs-nav {
  padding: 1px 2px;
  height: 32px;
  width: 220px;
  background: #eeeeee;
  border-radius: 6px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}
/deep/ .ant-tabs-nav-wrap {
  margin-bottom: 2px;
}
/deep/ .ant-tabs-nav .ant-tabs-tab {
  height: 28px;
  width: 107px;
  text-align: center;
  line-height: 28px;
  background: #eeeeee;
  border-radius: 6px;
  color: #333;
  padding: 0;
  // border: 1px solid rgba(0, 0, 0, 0.12);
  margin: 0;
}
/deep/ .ant-tabs-nav .ant-tabs-tab-active {
  background: #0b61ff;
  border-radius: 6px;
  color: #fff;
  z-index: 10;
}
/deep/ .ant-tabs-nav-container {
  margin-bottom: 12px;
}
/deep/ .ant-tabs-ink-bar {
  display: none !important;
}
/deep/ .ant-tabs-bar {
  border: none;
}
.color-f55 {
  color: #f55f4e !important;
}
.remind-text {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #f5222d;
  line-height: 20px;
  margin-left: 12px;
  margin-top: 12px;
}
/deep/ .ant-modal-footer {
  text-align: center;
  border-top: none;
}
</style>
